﻿using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEngine;

public class BuildEditor : EditorWindow
{
    //static string abPathTest = "Assets/SgRes";
    //[MenuItem("打包/设置单个物体ab名称", false, 99)]
    //public static void SetAbName1()
    //{
    //    SetAssetBundleNameObj(abPathTest);
    //}

    //[MenuItem("打包/按照ab名称打包", false, 99)]
    //public static void StartBuild1()
    //{
    //    SetAssetBundleNameObj(abPathTest);
    //    BuildAssetBundle1();
    //}


    [MenuItem("打包/android", false, 99)]
    public static void BuildAssetBundleWithAndroid()
    {
        string root = Application.dataPath + "/abRes/Assetbundle";
        string rootPath = "ABRes/Assetbundle";

        List<AssetBundleBuild> buildListRes = new List<AssetBundleBuild>();
        RecursiveToAddABMaps(root, rootPath, ref buildListRes);

        string outPath = Application.streamingAssetsPath + "/AB";
        FixedPath(ref outPath);
        // 清理目标目录中的所有文件和子目录
        if (Directory.Exists(outPath))
        {
            Directory.Delete(outPath, true);  // 删除目录及其所有内容
        }
        Directory.CreateDirectory(outPath); // 重新创建干净的目录
        
        AssetBundleBuild[] buildMap = buildListRes.ToArray();
        BuildPipeline.BuildAssetBundles(outPath, buildMap, BuildAssetBundleOptions.ChunkBasedCompression, BuildTarget.Android);
        Debug.LogError("========打包完成====" + outPath);
    }  
    
    [MenuItem("打包/ios", false, 99)]
    public static void BuildAssetBundleWithIOS()
    {
        string root = Application.dataPath + "/abRes/Assetbundle";
        string rootPath = "ABRes/Assetbundle";

        List<AssetBundleBuild> buildListRes = new List<AssetBundleBuild>();
        RecursiveToAddABMaps(root, rootPath, ref buildListRes);

        string outPath = Application.streamingAssetsPath + "/AB";
        FixedPath(ref outPath);
        // 清理目标目录中的所有文件和子目录
        if (Directory.Exists(outPath))
        {
            Directory.Delete(outPath, true);  // 删除目录及其所有内容
        }
        Directory.CreateDirectory(outPath); // 重新创建干净的目录
        
        AssetBundleBuild[] buildMap = buildListRes.ToArray();
        BuildPipeline.BuildAssetBundles(outPath, buildMap, BuildAssetBundleOptions.ChunkBasedCompression, BuildTarget.iOS);
        Debug.LogError("========打包完成====" + outPath);
    }   
    
    [MenuItem("打包/web", false, 99)]
    public static void BuildAssetBundleWithWEB()
    {
        string root = Application.dataPath + "/abRes/Assetbundle";
        string rootPath = "ABRes/Assetbundle";

        List<AssetBundleBuild> buildListRes = new List<AssetBundleBuild>();
        RecursiveToAddABMaps(root, rootPath, ref buildListRes);
        
        string outPath = Application.streamingAssetsPath + "/AB";
        FixedPath(ref outPath);
        
        
        // 清理目标目录中的所有文件和子目录
        if (Directory.Exists(outPath))
        {
            Directory.Delete(outPath, true);  // 删除目录及其所有内容
        }
        Directory.CreateDirectory(outPath); // 重新创建干净的目录
        
        /*if (!Directory.Exists(dst))
        {
            Directory.CreateDirectory(dst);
        }*/
        
        AssetBundleBuild[] buildMap = buildListRes.ToArray();
        BuildPipeline.BuildAssetBundles(outPath, buildMap,BuildAssetBundleOptions.AppendHashToAssetBundleName | BuildAssetBundleOptions.ChunkBasedCompression | UnityEditor.BuildAssetBundleOptions.DisableWriteTypeTree | BuildAssetBundleOptions.None, BuildTarget.WebGL);
        Debug.LogError("========打包完成====" + outPath);
    }
    

    //[MenuItem("打包/按照文件夹ab名称打包", false, 99)]
    //public static void StartBuild2()
    //{
    //    BuildAssetBundle1();
    //}


    //[MenuItem("打包/删除BundleName", false, 99)]
    //public static void DeleteBundleName()
    //{
    //    isClear = true;
    //    SetAssetBundleNameDir(abPathTest);

    //    SetAbName2();

    //    SetAssetBundleNameObj(abPathTest);
    //    isClear = false;
    //}

    private static void SetAssetBundleNameDir(string abPath)
    {
        DirectoryInfo dirInfo = new DirectoryInfo(abPath);


        string dirName = dirInfo.Name;

        if (isClear)
            dirName = "";

        string filePath = dirInfo.FullName.Replace('\\', '/');
        filePath = filePath.Replace(Application.dataPath, "Assets");
        //Debug.LogError("======filePath========" + filePath);
        AssetImporter ai = AssetImporter.GetAtPath(filePath);
        ai.assetBundleName = dirName;
        //SetAssetBundleNameDir(dirInfo.FullName);

        //DirectoryInfo[] dirs = dirInfo.GetDirectories();
        //for (int i = 0; i < dirs.Length; i++)
        //{
        //    SetAssetBundleNameDir(dirs[i].FullName);
        //}
    }


    private static bool isClear = false;
    private static void SetAssetBundleNameObj(string abPath)
    {
        DirectoryInfo dirInfo = new DirectoryInfo(abPath);
        string dirName = dirInfo.Name;

        if (isClear)
            dirName = "";

        FileSystemInfo[] files = dirInfo.GetFileSystemInfos();
        foreach (FileSystemInfo file in files)
        {
            if (file is FileInfo && file.Extension != ".meta" && file.Extension != ".txt")
            {
                string filePath = file.FullName.Replace('\\', '/');

                //string assetbundleName = dirName + "/" + dirName;

                filePath = filePath.Replace(Application.dataPath, "Assets");
                AssetImporter ai = AssetImporter.GetAtPath(filePath);
                ai.assetBundleName = dirName;
            }
            else if (file is DirectoryInfo)
            {
                //string filePath = file.FullName.Replace('\\', '/');
                //filePath = filePath.Replace(Application.dataPath, "Assets");
                //AssetImporter ai = AssetImporter.GetAtPath(filePath);
         
                //ai.assetBundleName = dirName;
                SetAssetBundleNameObj(file.FullName);
            }
        }
    }

    private static void BuildAssetBundle1()
    {
        string outPath = Application.streamingAssetsPath + "/../../" + "AssetBundles";
        DirectoryInfo abDir = new DirectoryInfo(outPath);
        if (!abDir.Exists)
        {
            abDir.Create();
        }
        BuildPipeline.BuildAssetBundles(abDir.FullName, BuildAssetBundleOptions.ChunkBasedCompression, BuildTarget.Android);
        Debug.LogError("========打包完成====" + outPath);
    }


    public static void RecursiveToAddABMaps(string resRoot, string rootPathInProject, ref List<AssetBundleBuild> abBuildMap)
    {
        // 指定路径下的全部文件的全路径名
        string[] names = Directory.GetFiles(resRoot);

        // 指定路径下的全部文件夹的全路径名
        string[] dirs = Directory.GetDirectories(resRoot);

        // 文件夹路径
        string folderDir = null;
        // 包名
        string assetbundleName = null;

        if (null == folderDir)
        {
            folderDir  = Application.dataPath + "/" + rootPathInProject + "/";
            if (folderDir.Length <= resRoot.Length)
            {
                assetbundleName = resRoot.Substring(folderDir.Length);
            }
        }

        // 文件全路径名
        string fileFullName = null;
        string assetBundleFullName = assetbundleName + ".ab";
        List<string> assetNames = new List<string>();

        for (int i = 0; i < names.Length; i++)
        {
            fileFullName = names[i];

            // 排除.meta文件
            string ext = Path.GetExtension(fileFullName);
            if (ext.EndsWith(".meta", System.StringComparison.Ordinal) || ext.Contains(".DS_Store")
                || ext.EndsWith(".back", System.StringComparison.Ordinal))
            {
                continue;
            }
            FixedPath(ref fileFullName);
            string AssetsPath = "Assets" + fileFullName.Substring(Application.dataPath.Length);
     

            AssetImporter infor = AssetImporter.GetAtPath(AssetsPath);
            if (null != infor)
            {
                assetNames.Add(AssetsPath);
            }
        }

        if (assetNames.Count > 0)
        {
            AssetBundleBuild abBuild = new AssetBundleBuild();
   
            abBuild.assetNames = assetNames.ToArray();
            abBuild.assetBundleName = assetBundleFullName;
            abBuildMap.Add(abBuild);
        }

        //处理子文件夹
        for (int i = 0; i < dirs.Length; i++)
        {
            string d = dirs[i];
            if (d.Contains(".svn")) continue;
            FixedPath(ref d);
            RecursiveToAddABMaps(d, rootPathInProject, ref abBuildMap);
        }
    }

    public static void FixedPath(ref string path)
    {
        path = path.Replace('\\', '/');
    }
}
